package org.optaplanner.examples.apsplanning.dao;

import org.optaplanner.examples.apsplanning.domain.MachiningType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author andaolong
 * @time 2021/3/27-14:44
 * @describe从数据库中获取数据
 */
@Component
public class MachiningTypeDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    //根据deviceId查询device对应的machiningType的list，用来向device对象里面填入machiningType
    public List<MachiningType> getMachiningTypeListByDeviceIdFromDB(String deviceId) {

        //根据deviceId查询到machiningType的list
        String sql = "select machining_type from device natural left join device_info where device_id= \"" + deviceId + "\"";

        //将查询到的device_id对应的machiningType存到一串<MachiningType>的list里面并返回
        //这里因为数据库中存储的machiningType是String类型的一个字符串，而我们的Process里面machiningType是MachiningType类型，
        //所以通过BeanPropertyRowMapper没法直接获取到，所以重写了一下这个RomMapper方法，转化一下
        //参考链接：https://www.jianshu.com/p/be60a81e2fe7
        //return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(MachiningType.class));
        List<MachiningType> machiningTypeList = null;
        machiningTypeList = jdbcTemplate.query(sql, new RowMapper<MachiningType>() {
            @Override
            public MachiningType mapRow(ResultSet resultSet, int i) throws SQLException {
                MachiningType machiningTypeTemp;

                //将获得的String类型的machining_type转换为MachiningType类型的machiningType
                String machiningTypeStr = resultSet.getNString("machining_type");
                machiningTypeTemp = new MachiningType(1, machiningTypeStr);

                return machiningTypeTemp;
            }
        });

        return machiningTypeList;
    }
}
